var http = require('http');
var util = require('util');
var xmlReader = require('xmlreader');
var logger = require("./models/logger")

var SmsUtils = {
    //计算文字需要多少条短信发送
    getSmsCount: function(s) {
        if (s == "" || !s)
            return 0;
        var len = s.replace(/[^\u0000-\u00ff]/g, "aa").length;
        console.log(len);
        return parseInt((len + 69) / 70);
    },
    //通知短信
    NoticeSms: function(phones, msg, cb) {
        if (!phones || phones.length < 1 || !msg)
            return;
        var length = phones.length;

        var receiver = '';
        for (var i = 0; i < length; i++) {
            if (phones[i].replace(/[^0-9]/g, '').length == 11) {
                receiver += phones[i].replace(/[^0-9]/g, '') + ',';
            }
        }
        receiver = receiver.substr(0, receiver.length - 1);
        //logger.debug('NoticeSms, receiver:' + receiver);
        SmsUtils.sendSms(receiver, msg, length, cb);
    },

    httpRequest: function(type, receiver, msg, number, cb) {
        //logger.debug('httpRequest(' + type + ', ' + receiver + ', ' + msg + ', ' + number);
        var smsid = '6379';
        var smsaccount = 'MDCBJYHB';
        var smspassword = 'mdc_kaimen2808';
        var path;
        if (type == 0) //检查短信内容
            path = "/sms.aspx?action=checkkeyword&userid=" + smsid +
            "&account=" + smsaccount + "&password=" + smspassword +
            "&content=" + encodeURI(msg);
        else if (type == 1) //发送短信
            path = "/sms.aspx?action=send&userid=" + smsid + "&checkcontent=0" +
            "&account=" + smsaccount + "&password=" + smspassword +
            "&mobile=" + receiver + "&content=" + encodeURI(msg) +
            "&countnumber=" + number + "&mobilenumber=" + number +
            "&telephonenumber=0";
        else
            return;

        var opt = {
            method: 'POST',
            host: 'www.qf106.com',
            port: 80,
            path: path
        };
        //logger.debug('httpRequest, opt:' + util.inspect(opt));

        SmsUtils.cbHttp(3, type, opt, cb);
    },

    //非法关键词查询，并执行回调函数
    checkContent: function(msg, cb) {
        SmsUtils.httpRequest(0, "", msg, 0, cb);
    },

    //发送短信，并执行回调函数
    //desc:停用沈阳短信平台,启用杭州短信平台. auth:张立成, date:2014-08-14
    sendSms: function(receiver, msg, number, cb) {
        //短信开关
        // if (!Consts.SMS) return;
        //判断手机号是否合法
        if (!receiver || receiver.length < 11) return;
        //沈阳拇指短信通道
        //SmsUtils.httpRequest(1, receiver, msg, number, cb);
        //杭州图门短信通道
        var maxCount = 50; //单次MT上限
        var phoneArray = receiver.split(",");
        var phoneCount = phoneArray.length;
        if (phoneCount <= maxCount) { //单次发送
            SmsUtils.topmisLogin(function(token) {
                SmsUtils.topmisSend(token, receiver, msg, cb);
            });
        } else { //多次发送
            var sendCount = Math.ceil(phoneCount / maxCount);
            var num;
            var sliceOfArray;
            var phoneString;
            SmsUtils.topmisLogin(function(token) {
                for (var i = 1; i <= sendCount; i++) {
                    num = ((maxCount * i) - maxCount);
                    sliceOfArray = phoneArray.slice(num, num + maxCount);
                    phoneString = sliceOfArray.join(",");
                    //logger.debug("===SMS Utils sendSms() phoneString===" + phoneString + "===i===" + i + "===num===" + num + "===sendCount===" + sendCount);
                    SmsUtils.topmisSend(token, phoneString, msg, cb);
                }
            });
        }
    },

    cbHttp: function(count, type, opt, cb) {
        if (count <= 0)
            return;
        //logger.debug('cmbSms(count, type, opt, cb):' + count + ',' + type);

        var request_timer = null;
        var req = null;
        // 请求5秒超时
        request_timer = setTimeout(function() {
            req.abort();
            //logger.debug('Sms:Request Timeout.');
        }, 5000);

        req = http.request(opt, function(res) {
            clearTimeout(request_timer);

            // 等待响应30秒超时
            var response_timer = setTimeout(function() {
                res.destroy();
                SmsUtils.cbHttp(count--, type, opt, cb);
                //logger.debug('Sms:Response Timeout.');
            }, 30000);

            //logger.debug("send sms http response status=" + res.statusCode);
            if (res.statusCode == 200) {
                var body = "";
                res.on('data', function(data) {
                    body += data;
                }).on('end', function() {
                    clearTimeout(response_timer);
                    //logger.debug("send sms http response body:" + body);
                    //解析body内容（xml格式），并返回给调用者
                    xmlReader.read(body, function(error, res) {
                        if (error) {
                            logger.error('send sms error:' + error);
                            cb(103);
                            return;
                        }
                        console.log('---------recv content:\n' + res.returnsms);
                        if (type == 0) {
                            if (res.returnsms.message.text(0) == "没有包含屏蔽词")
                                cb(0);
                            else
                                cb(103, res.returnsms.returnstatus.text(0));
                        } else if (type == 1) {
                            if (res.returnsms.returnstatus.text(0) == "Success")
                                cb(0);
                            else
                                cb(103);
                        }
                    });
                });
            }
        });
        req.end();
    },

    //登录
    topmisLogin: function(cb) {
        var path = "/app/sms/cloud/auth.form";
        var loginData = "<loginKey><accountId>bochy2015</accountId><password>sq1973001</password></loginKey>";
        var opt = {
            method: 'POST',
            host: 'www.topmis.cn',
            port: 80,
            path: path,
            headers: {
                'Content-Type': 'application/xml; charset=UTF-8',
                'Accept': 'application/xml',
                'Content-Length': loginData.length
            }
        };
        var req = null;
        req = http.request(opt, function(res) {
            if (res.statusCode == 200) {
                var body = "";
                res.on('data', function(data) {
                    body += data;
                }).on('end', function() {
                    //logger.debug("===SMS Utils topmisLogin() Response Body===" + body);
                    //解析返回body获取token
                    xmlReader.read(body, function(error, res) {
                        if (error) {
                            logger.error("===SMS Utils topmisLogin() Response XML Error===" + error);
                            cb(103);
                            return;
                        } else {
                            cb(res.result.data.token.text());
                        }
                    });
                });
            } else {
                logger.error("===SMS Utils topmisLogin() Response Status===" + res.statusCode);
                cb(103);
                return;
            }
        });
        req.write(loginData);
        req.end();
    },

    //发送短信
    topmisSend: function(vtoken, vreceivers, vmsg, cb) {
        var tmpmsg = vmsg.replace(/[^\u0000-\u00FF]/g, function($0) {
            return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;")
        });
        var sendmsg = "<sm><accountId>bochy2015</accountId><token>" + vtoken + "</token><content>" + tmpmsg + "&#x3010;&#x535a;&#x521b;&#x534e;&#x5b87;&#x3011;</content><targetPhoneNo>" + vreceivers + "</targetPhoneNo><customId>" + vreceivers + "</customId><isUrgent>1</isUrgent></sm>";
        var sendpath = "/app/sms/cloud/submit.form";
        var sendopt = {
            method: 'POST',
            host: 'www.topmis.cn',
            port: 80,
            path: sendpath,
            headers: {
                'Content-Type': 'application/xml; charset=UTF-8',
                'Accept': 'application/xml',
                'Content-Length': sendmsg.length
            }
        };
        var sendreq = null;
        sendreq = http.request(sendopt, function(response) {
            //logger.debug("===SMS Utils topmisSend() Response Status===" + response.statusCode + "===Post Info===" + sendmsg);
            if (response.statusCode == 200) {
                var sendbody = "";
                response.setEncoding("utf8");
                response.on('data', function(data) {
                    sendbody += data;
                }).on('end', function() {
                    //logger.debug("===SMS Utils topmisSend() Response Body===" + sendbody);
                    //解析返回body获取code
                    xmlReader.read(sendbody, function(error, res) {
                        if (error) {
                            logger.error("===SMS Utils topmisSend() Response XML Error===" + error);
                            cb(103);
                            return;
                        } else {
                            var sendResult = res.result.code.text();
                            cb(0);
                        }
                    });
                });
            } else {
                logger.error("===SMS Utils topmisSend() Response Status===" + response.statusCode + "===Post Info===" + sendmsg);
                cb(103);
                return
            }
        });
        sendreq.write(sendmsg);
        sendreq.end();
    }
};

module.exports = SmsUtils;